package org.lord.slark.numbers.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.Toast;

import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;

import org.lord.slark.numbers.R;
import org.lord.slark.numbers.entity.ShareEntity;
import org.lord.slark.numbers.fragments.FragmentAdd;
import org.lord.slark.numbers.fragments.FragmentNumbers;
import org.lord.slark.numbers.fragments.FragmentSaints;
import org.lord.slark.numbers.utils.ELog;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class MainActivity extends FragmentActivity implements
        CompoundButton.OnCheckedChangeListener {
    private static final int MSG_SUCCESS = 0;
    private static final int MSG_FAIL_LAMB = 1;
    private static final int MSG_FAIL_SS = 2;
    private static final int MSG_FAIL_SR = 3;
    private static final int MSG_EXISTS = 4;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = "";
            switch (msg.what) {
                case MSG_SUCCESS:
                    result = "数据导入成功！";
                    break;
                case MSG_FAIL_LAMB:
                    result = "导入小羊失败！";
                    break;
                case MSG_FAIL_SS:
                    result = "导入牧养设置失败！";
                    break;
                case MSG_FAIL_SR:
                    result = "导入牧养记录失败！";
                    break;
                case MSG_EXISTS:
                    result = "小羊已存在！";
                    break;
                default:
                    break;
            }
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
            mDialog.dismiss();
        }
    };
    private FragmentManager mFmanager;
    private RadioButton radioAdd;
    private RadioButton radioNumber;
    private RadioButton radioSaints;
    private int pagecounter;
    private AlertDialog mExitDialog;
    private ArrayList<Fragment> fragmentList;
    private ViewPager mPager;
    private ProgressDialog mDialog;
    private boolean needimport = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        UmengUpdateAgent.setUpdateOnlyWifi(false);
        UmengUpdateAgent.update(this);
        mFmanager = getSupportFragmentManager();
        initView();

        mDialog = new ProgressDialog(this);
        mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mDialog.setTitle(getString(R.string.systeminfo));
        mDialog.setMessage("正在导入小羊数据，请稍后...");
        mDialog.setCancelable(false);
        mDialog.setIcon(R.mipmap.ic_launcher);
        processIntent();
    }

    private void initView() {
        mPager = (ViewPager) findViewById(R.id.vPager);
        radioAdd = (RadioButton) findViewById(R.id.tabadd);
        radioNumber = (RadioButton) findViewById(R.id.tabnumber);
        radioSaints = (RadioButton) findViewById(R.id.tabsaints);

        radioNumber.setOnCheckedChangeListener(this);
        radioAdd.setOnCheckedChangeListener(this);
        radioSaints.setOnCheckedChangeListener(this);

        fragmentList = new ArrayList<Fragment>();
        Fragment f1 = new FragmentAdd();
        Fragment f2 = new FragmentNumbers();
        Fragment f3 = new FragmentSaints();
        fragmentList.add(f1);
        fragmentList.add(f2);
        fragmentList.add(f3);
        mPager.setAdapter(new MyFragmentPagerAdapter(
                getSupportFragmentManager(), fragmentList));
        mPager.setOnPageChangeListener(new MyOnPageChangeListener());
        radioAdd.setChecked(true);
        mPager.setCurrentItem(0);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//         getMenuInflater().inflate(R.menu.menu_export, menu);
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            switch (buttonView.getId()) {
                case R.id.tabadd:
                    mPager.setCurrentItem(0);
                    MobclickAgent.onEvent(MainActivity.this, "AddNumbers");
                    break;
                case R.id.tabnumber:
                    mPager.setCurrentItem(1);
                    MobclickAgent.onEvent(MainActivity.this, "ResearchNumbers");
                    break;
                case R.id.tabsaints:
                    mPager.setCurrentItem(2);
                    MobclickAgent.onEvent(MainActivity.this, "AllSaints");
                    break;
                default:
                    break;
            }
            pagecounter = mFmanager.getBackStackEntryCount();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        /*if (item.getItemId() == R.id.menuexport) {
            if (!mDialog.isShowing()) {
                mDialog.show();
            }
            new Thread(new Runnable() {

                @Override
                public void run() {
                    MobclickAgent.onEvent(MainActivity.this, "exportlambs");
                    exportToXls();
                }
            }).start();
        }*/
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (mFmanager.getBackStackEntryCount() == pagecounter) {
            exit();
            return;
        }
        if (!mFmanager.popBackStackImmediate()) {
            exit();
            return;
        }
    }

    

    /*private void getData() {
        listlamb.clear();
        try {
            Cursor c  = ShepherdDB.getInstance(this).getWritableDatabase().query(Saint.TABLE_NAME, null, null, null, null, null, null);
            while (c.moveToNext()) {
                Saint lamb = new Saint();
                lamb.setId(c.getInt(c.getColumnIndex(Saint.COLUMN_ID)));
                lamb.setAdd_date(c.getLong(c.getColumnIndex(Saint.COLUMN_ADD_DATE)));
                lamb.setAddress(c.getString(c.getColumnIndex(Saint.COLUMN_ADDRESS)));
                lamb.setBaptized_time(c.getLong(c.getColumnIndex(Saint.COLUMN_BAPTIZED_DATE)));
                lamb.setBirth_date(c.getLong(c.getColumnIndex(Saint.COLUMN_BIRTH_DATE)));
                lamb.setFirst_meet_date(c.getLong(c.getColumnIndex(Saint.COLUMN_FIRST_MEET_DATE)));
                lamb.setGender(c.getInt(c.getColumnIndex(Saint.COLUMN_GENDER)));
                lamb.setGroup_id(c.getInt(c.getColumnIndex(Saint.COLUMN_GROUP_ID)));
                lamb.setIsBaptized(c.getInt(c.getColumnIndex(Saint.COLUMN_IS_BAPTIZED)));
                lamb.setName(c.getString(c.getColumnIndex(Saint.COLUMN_NAME)));
                lamb.setPhone(c.getString(c.getColumnIndex(Saint.COLUMN_PHONE)));
                lamb.setRemark(c.getString(c.getColumnIndex(Saint.COLUMN_REMARK)));
                lamb.setStatus(c.getInt(c.getColumnIndex(Saint.COLUMN_STATUS)));
                lamb.setType(c.getInt(c.getColumnIndex(Saint.COLUMN_TYPE)));

                listlamb.add(lamb);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }*/

    private void exit() {
        if (mExitDialog == null) {
            mExitDialog = new AlertDialog.Builder(this).setTitle(getString(R.string.systeminfo))
                    .setMessage("确定退出程序么?")
                    .setPositiveButton(getString(R.string.ok), new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            MobclickAgent.onKillProcess(MainActivity.this);
                            MainActivity.this.finish();
                            android.os.Process.killProcess(android.os.Process
                                    .myPid());
                        }
                    }).setNegativeButton(getString(R.string.cancel), null).create();
        }
        mExitDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        ELog.d("xusai", "onNewIntent---------------------");
        setIntent(intent);
        processIntent();

    }

    private void processIntent() {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        int id = intent.getIntExtra("LambID", -1);
        if (id == -1) {
            Uri uri = intent.getData();
            if (uri != null) {
                final String path = uri.getPath();
                ELog.d("xusai", "uri path++++++++++:" + path);
                String gson = null;
                try {
                    InputStream inputStream = getContentResolver().openInputStream(uri);
                    String sss = convertStreamToString(inputStream);
                    gson = new String(Base64.decode(sss, Base64.NO_WRAP));
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }
                if (gson == null) {
                    return;
                }
                insertToDB(gson);
            }
        }
    }

    public String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

    private void insertToDB(String origin) {
        Gson gson = new Gson();
        ShareEntity se = gson.fromJson(origin, ShareEntity.class);
//        boolean a = insertLamb(se.getLamb());
//        if (!needimport) {
//            return;
//        }
//        boolean b = insertShepherdSetting(se.getSs());
//        boolean c = insertShepherdRecord(se.getSrecord());
//        if (a && b && c) {
//            mHandler.sendEmptyMessage(MSG_SUCCESS);
//        } else if (!a) {
//            mHandler.sendEmptyMessage(MSG_FAIL_LAMB);
//        } else if (!b) {
//            mHandler.sendEmptyMessage(MSG_FAIL_SS);
//        } else {
//            mHandler.sendEmptyMessage(MSG_FAIL_SR);
//        }
    }

//    private boolean insertLamb(Saint lamb) {
//        String sqlquery = "select * from " + Saint.TABLE_NAME + " where " + Saint.COLUMN_NAME + "='" + lamb.getName() + "';";
//        Cursor c = ShepherdDB.getInstance(this).getWritableDatabase().rawQuery(sqlquery, null);
//        if (c.moveToNext()) {
//            mHandler.sendEmptyMessage(MSG_EXISTS);
//            needimport = false;
//            return true;
//        }
//        String sqlinsert = "insert into " + Saint.TABLE_NAME + "  values (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
//        try {
//            ShepherdDB.getInstance(this).getWritableDatabase().execSQL(sqlinsert, new Object[]{lamb.getAdd_date(), lamb.getAddress(),
//                    lamb.getBaptized_time(), lamb.getBirth_date(), lamb.getEmail(), lamb.getFirst_meet_date(), lamb.getGender(), lamb.getIsBaptized(),
//                    lamb.getName(), lamb.getPhone(), lamb.getRemark(), lamb.getStatus(), lamb.getType()});
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//            ELog.d("xusai", "insert into Saint error!");
//        }
//        return false;
//    }

//    private boolean insertShepherdSetting(MeetingNumber ss) {
//        ELog.d("xusai", "ss:" + ss);
//        if (ss == null) {
//            return true;
//        }
//        try {
//            String sql = "insert into " + MeetingNumber.TABLE_NAME + " values (NULL, ?, ?, ?, ?, ?);";
//            ShepherdDB.getInstance(this).getWritableDatabase().execSQL(sql, new Object[]{ss.getData(), ss.getFrequency(),
//                    ss.getStartTime(), ss.getStatus(), ss.getLambID()});
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return false;
//    }

//    private boolean insertShepherdRecord(List<ShepherdRecord> list) {
//        if (list == null) {
//            return true;
//        }
//        boolean flag = true;
//        try {
//            String sql = "insert into " + ShepherdRecord.TABLE_NAME + " values (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
//            ShepherdDB.getInstance(this).getWritableDatabase().beginTransaction();
//            for (ShepherdRecord sr : list) {
//                ShepherdDB.getInstance(this).getWritableDatabase().execSQL(sql, new Object[]{sr.getAddDate(),
//                        sr.getAddress(), sr.getAppreciation(), sr.getCherish(), sr.getContent(), sr.getLambId(),
//                        sr.getPreparation(), sr.getRemark(), sr.getStartTime(), sr.getEndTime(),
//                        sr.getShortcoming(), sr.getWay()});
//            }
//            ShepherdDB.getInstance(this).getWritableDatabase().setTransactionSuccessful();
//            ShepherdDB.getInstance(this).getWritableDatabase().endTransaction();
//        } catch (Exception e) {
//            e.printStackTrace();
//            flag = false;
//        }
//        if (flag) {
//            return true;
//        }
//        return false;
//    }

    @Override
    protected void onResume() {
        super.onResume();
        ELog.d("xusai", "needimport:" + needimport);
        needimport = true;
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
        ArrayList<Fragment> list;
        Fragment mFragmentAtPos0;

        public MyFragmentPagerAdapter(FragmentManager fm, ArrayList<Fragment> list) {
            super(fm);
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Fragment getItem(int position) {
            return list.get(position);
        }
    }

    public class MyOnPageChangeListener implements OnPageChangeListener {
        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageSelected(int arg0) {
            switch (arg0) {
                case 0:
                    mPager.setCurrentItem(0);
                    radioAdd.setChecked(true);
                    break;
                case 1:
                    mPager.setCurrentItem(1);
                    radioNumber.setChecked(true);
                    break;
                case 2:
                    mPager.setCurrentItem(2);
                    radioSaints.setChecked(true);
                    break;
                default:
                    break;
            }
            pagecounter = mFmanager.getBackStackEntryCount();
        }

    }
}
